<!-- eslint-disable regexp/no-unused-capturing-group -->
<script>
import { register } from '@/api/user'
import { computed, ref } from 'vue'

export default {
  setup() {
    const form = ref(null)
    const accountTypeIndex = ref(0)
    const passwordStrength = ref(0)

    const formData = ref({
      email: '',
      phone: '',
      password: '',
      confirmPassword: '',
      nickname: '',
      gender: '保密',
      agreement: false,
    })

    const genderOptions = [
      { text: '男', value: '男' },
      { text: '女', value: '女' },
      { text: '保密', value: '保密' },
    ]

    const strengthText = computed(() => {
      const texts = ['弱', '中', '强']
      return texts[passwordStrength.value - 1] || ''
    })

    const rules = {
      email: { // 邮箱专用规则
        rules: [
          {
            required: accountTypeIndex.value === 0,
            errorMessage: '请输入邮箱',
          },
          {
            validateFunction: (rule, value) => {
              return accountTypeIndex.value !== 0 || /^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/.test(value)
            },
            errorMessage: '邮箱格式不正确',
          },
        ],
      },
      phone: { // 手机号专用规则
        rules: [
          {
            required: accountTypeIndex.value === 1,
            errorMessage: '请输入手机号',
          },
          {
            validateFunction: (rule, value) => {
              return accountTypeIndex.value !== 1 || /^1[3-9]\d{9}$/.test(value)
            },
            errorMessage: '手机号格式不正确',
          },
        ],
      },
      password: {
        rules: [
          { required: true, errorMessage: '请输入密码' },
          { minLength: 6, errorMessage: '密码不能少于6位' },
        ],
      },
      confirmPassword: {
        rules: [
          { required: true, errorMessage: '请确认密码' },
          {
            validateFunction: (rule, value, data) => {
              return value === data.password
            },
            errorMessage: '两次输入的密码不一致',
          },
        ],
      },
      nickname: {
        rules: [
          { required: true, errorMessage: '请输入昵称' },
        ],
      },
      agreement: {
        rules: [
          {
            validateFunction: (rule, value) => {
              return value === true
            },
            errorMessage: '请同意用户协议',
          },
        ],
      },
    }

    const checkPasswordStrength = (password) => {
      let strength = 0
      if (password.length >= 6)
        strength++
      if (/[A-Z]/.test(password) && /[a-z]/.test(password))
        strength++
      if (/\d/.test(password) && /[^A-Z0-9]/i.test(password))
        strength++
      passwordStrength.value = strength
    }

    const onAccountTypeChange = (e) => {
      accountTypeIndex.value = e.currentIndex
      formData.value.account = ''
    }

    const onAgreementChange = (e) => {
      formData.value.agreement = e.detail.value.length > 0
    }

    const handleRegister = async () => {
      try {
        const valid = await form.value.validate()
        if (!valid)
          return

        const registerData = {
          [accountTypeIndex.value === 0 ? 'email' : 'phone']: formData.value[accountTypeIndex.value === 0 ? 'email' : 'phone'],
          password: formData.value.password,
          nickname: formData.value.nickname,
          gender: formData.value.gender,
        }

        await register(registerData)

        uni.showToast({
          title: '注册成功',
          icon: 'success',
        })

        setTimeout(() => {
          uni.navigateTo({
            url: '/pages/login/index',
          })
        }, 1500)
      }
      catch (error) {
        console.error('注册失败:', error)
      }
    }

    const goToLogin = () => {
      uni.navigateTo({
        url: '/pages/login/index',
      })
    }

    const goToAgreement = () => {
      uni.navigateTo({
        url: '/pages/agreement/index',
      })
    }

    return {
      form,
      formData,
      rules,
      accountTypeIndex,
      passwordStrength,
      strengthText,
      genderOptions,
      onAccountTypeChange,
      onAgreementChange,
      checkPasswordStrength,
      handleRegister,
      goToLogin,
      goToAgreement,
    }
  },
}
</script>

<template>
  <view class="register-container">
    <view class="register-header">
      <text class="title">
        用户注册
      </text>
    </view>

    <view class="register-form">
      <uni-forms ref="form" :model-value="formData" :rules="rules">
        <uni-forms-item name="accountType">
          <uni-segmented-control
            :current="accountTypeIndex"
            :values="['邮箱注册', '手机注册']"
            @click-item="onAccountTypeChange"
          />
        </uni-forms-item>

        <uni-forms-item :name="accountTypeIndex === 0 ? 'email' : 'phone'">
          <uni-easyinput
            v-model="formData[accountTypeIndex === 0 ? 'email' : 'phone']"
            :placeholder="accountTypeIndex === 0 ? '请输入邮箱' : '请输入手机号'"
          />
        </uni-forms-item>

        <uni-forms-item name="password">
          <uni-easyinput
            v-model="formData.password"
            type="password"
            placeholder="请输入密码"
            @input="checkPasswordStrength"
          />
          <view class="password-strength">
            <text>密码强度：</text>
            <view class="strength-bars">
              <view
                v-for="(item, index) in 3"
                :key="index"
                class="strength-bar"
                :class="{ active: passwordStrength >= index + 1 }"
              />
            </view>
            <text class="strength-text">
              {{ strengthText }}
            </text>
          </view>
        </uni-forms-item>

        <uni-forms-item name="confirmPassword">
          <uni-easyinput
            v-model="formData.confirmPassword"
            type="password"
            placeholder="请确认密码"
          />
        </uni-forms-item>

        <uni-forms-item name="nickname">
          <uni-easyinput
            v-model="formData.nickname"
            placeholder="请输入昵称"
          />
        </uni-forms-item>

        <uni-forms-item name="gender">
          <uni-data-checkbox
            v-model="formData.gender"
            :localdata="genderOptions"
          />
        </uni-forms-item>

        <uni-forms-item name="agreement">
          <checkbox-group @change="onAgreementChange">
            <label class="agreement-label">
              <checkbox :checked="formData.agreement" />
              <text>我已阅读并同意</text>
              <text class="agreement-link" @click="goToAgreement">《用户协议》</text>
            </label>
          </checkbox-group>
        </uni-forms-item>
      </uni-forms>

      <button class="register-btn" type="primary" @click="handleRegister">
        注册
      </button>

      <view class="login-link" @click="goToLogin">
        已有账号？立即登录
      </view>
    </view>
  </view>
</template>

<style lang="scss" scoped>
.register-container {
  padding: 40rpx;

  .register-header {
    text-align: center;
    margin-bottom: 60rpx;

    .title {
      font-size: 36rpx;
      font-weight: bold;
      color: #333;
    }
  }

  .register-form {
    .password-strength {
      display: flex;
      align-items: center;
      margin-top: 10rpx;
      font-size: 24rpx;
      color: #666;

      .strength-bars {
        display: flex;
        gap: 10rpx;
        margin: 0 10rpx;

        .strength-bar {
          width: 40rpx;
          height: 10rpx;
          background-color: #ddd;
          border-radius: 5rpx;

          &.active {
            &:nth-child(1) { background-color: #ff4d4f; }
            &:nth-child(2) { background-color: #faad14; }
            &:nth-child(3) { background-color: #52c41a; }
          }
        }
      }
    }

    .agreement-label {
      display: flex;
      align-items: center;
      font-size: 28rpx;
      color: #666;

      .agreement-link {
        color: #007AFF;
      }
    }

    .register-btn {
      width: 100%;
      height: 88rpx;
      line-height: 88rpx;
      margin: 40rpx 0;
      background-color: #007AFF;
      border-radius: 44rpx;
    }

    .login-link {
      text-align: center;
      font-size: 28rpx;
      color: #007AFF;
    }
  }
}
</style>
